import { customRef } from "vue";

/**
 * 防抖函数 
 * @param func 函数
 * @param wait 防抖时间
 * @returns 
 */
export function debounce<T extends (...args: any[]) => any>(func: T, wait: number = 1000): (...args: Parameters<T>) => void {
  let timeoutId: number;
  return function debounced(this: any, ...args: Parameters<T>): void {
    clearTimeout(timeoutId);
    timeoutId = window.setTimeout(() => {
      func.apply(this, args);
    }, wait);
  };
}

/**
 * 防抖Ref
 * @param value 
 * @param wait 
 * @returns 
 */
export function debounceRef<TValue>(value: TValue, wait: number = 1000) {
  let timer: number;
  return customRef((track, trigger) => {
    return {
      get() {
        track();
        return value;
      },
      set(val) {
        clearTimeout(timer);
        timer = setTimeout(() => {
          value = val;
          trigger();
        }, wait);
      },
    }
  })
}